package com.cma.common.redis;

import redis.clients.jedis.exceptions.JedisDataException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ObjectsTranscoder {
	public static byte[] serialize(List<?> list) {
		
		byte[] rv = null;
		ByteArrayOutputStream bos = null;
		ObjectOutputStream os = null;
		try {
			bos = new ByteArrayOutputStream();
			os = new ObjectOutputStream(bos);
			for (Object field : list) {
				os.writeObject(field);
			}
			os.close();
			bos.close();
			rv = bos.toByteArray();
		} 
		catch(JedisDataException e)
		{ 
		}
		catch (IOException e) {
		} finally {
			try {
				if (os != null)
					os.close();
				if (bos != null)
					bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
		}
		return rv;
	}

	public static List<?> deserialize(byte[] in) {
		List<Object> list = new ArrayList<Object>();
		ByteArrayInputStream bis = null;
		ObjectInputStream is = null;
		try {
			if (in != null) {
				bis = new ByteArrayInputStream(in);
				is = new ObjectInputStream(bis);
				while (true) {
					Object field = (Object) is.readObject();
					if (field == null) {
						break;
					} else {
						list.add(field);
					}
				}
				is.close();
				bis.close();
			}
		}
		catch(EOFException e)
		{
		}
		catch (IOException e) {
			
		} catch (ClassNotFoundException e) {
			
		} finally {

			try {
				if (is != null)
					is.close();
				if (bis != null)
					bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				
			}
		}
		return list;
	}

	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null; 
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {
			
			return null;
		}
	}

	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			
			return null;
		}
	}
}
